package com.llb666.java.leetcode;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 *
 * 给定一个整数数组numbers,从数组中找到两个满足相加之和等于目标数target
 * 假设每个输入只对应唯一的答案，而且不可以重复使用相同的元素
 * 返回两个数值的下标值，以数组的形式返回
 * Created by 斌~
 * 2021/4/27 15:46
 */
public class 两数之和 {
    public static void main(String[] args) {
        int [] numbers = {1,2,3,4,5,6};
        int target =10;

        int[] solution = solution(numbers, target);
        System.out.println("["+solution[0]+","+solution[1]+"]");
        int[] twoSearch = twoSearch(numbers, target);
        System.out.println("["+twoSearch[0]+","+twoSearch[1]+"]");
    }

    private static int[] solution (int [] numbers,int target){
        //定义一个map记录遍历中的 数值 以及 下标
        Map<Integer,Integer> map = new HashMap<>();
        for (int i = 0; i < numbers.length; i++) {
            //目标值-当前遍历数值 存在map中，直接返回结果
            if(map.containsKey(target-numbers[i])){
                return new int[]{map.get(target-numbers[i]),i};
            }
            map.put(numbers[i],i);
        }
        return new int[0];
    }

    /**
     * 二分查找法
     * @param numbers 数组
     * @param target 目标值
     * @return 下标数组
     */
    private static int[] twoSearch (int [] numbers,int target){
        Arrays.sort(numbers);
        for (int i = 0; i < numbers.length; i++) {
            int low = i, high =numbers.length-1;
            while(low <= high){
                int mid = (high-low)/2 +low;
                if(numbers[mid] == target-numbers[i]){
                    return new int[]{i,mid};
                }else if(numbers[mid] > target-numbers[i]){
                    high = mid -1;
                }else if(numbers[mid] < target-numbers[i]){
                    low = mid + 1;
                }
            }
        }
        return new int[0];
    }

}
